package com.boot.learning.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.boot.learning.domain.ErrorInfo;

/**
 * 统一异常处理 ： 通过使用@ControllerAdvice定义统一的异常处理类，
 * 而不是在每个Controller中逐个定义。 @ExceptionHandler用来定义函数针对的异常类型，
 * 最后将Exception对象和请求URL映射到error.html中
 * 
 * @version 1.0
 * @author fuhw
 */
@ControllerAdvice
public class UnifiedExceptionHandler {

	public static final String DEFAULT_ERROR_VIEW = "error";

	/**
	 * 处理500异常
	 * 
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 *         根据抛出的具体Exception类型匹配@ExceptionHandler中配置的异常类型来匹配错误映射和处理。
	 * @author fuhw
	 */
	@ExceptionHandler(value = BadRequestException.class)
	public ModelAndView defaultErrorHandler( HttpServletRequest req, BadRequestException e ) throws Exception{
		ModelAndView mav = new ModelAndView();
		mav.addObject( "exception", e );
		mav.addObject( "url", req.getRequestURL() );
		mav.setViewName( DEFAULT_ERROR_VIEW );
		return mav;
	}

	/**
	 * 处理404异常 
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 * @author fuhw
	 */
	@ResponseBody
	@ExceptionHandler(value = NotFoundException.class)
	public ErrorInfo<String> notFundErrorHandler( HttpServletRequest req, NotFoundException e ) throws Exception{
		ErrorInfo<String> r = new ErrorInfo<>();
		r.setMessage( e.getMessage() );
		r.setCode( ErrorInfo.ERROR );
		r.setData( "Some Data" );
		r.setUrl( req.getRequestURL().toString() );
		return r;
	}
}
